<template>
  <div class="dialogue-wrap">
    <div class="attachment-box" v-if="uploadFileList.length">
      <p class="ab-tips">仅识别附件中的文字</p>
      <div class="attachment-items">
        <div v-for="(file, i) of uploadFileList" :key="i" class="ab-item" @click="handleFilePreview(file)">
          <div class="ab-item-icon">
            <div v-if="file.loading" v-loading="true" class="ab-loading"></div>
            <svg
              v-else-if="!file.loading && isImageByMIME(file.raw.type)"
              width="32"
              height="32"
              viewBox="0 0 32 32"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M21.4237 7H10.5763C8.04887 7 6 8.94521 6 11.3447V20.6544C6 23.054 8.04887 24.9992 10.5763 24.9992H21.4237C23.9511 24.9992 26 23.054 26 20.6544V11.3447C26 8.94521 23.9511 7 21.4237 7Z"
                fill="#9AD2EC"
              ></path>
              <path
                d="M11.3448 14.2014C12.3922 14.2014 13.2413 13.3955 13.2413 12.4015C13.2413 11.4074 12.3922 10.6016 11.3448 10.6016C10.2974 10.6016 9.44824 11.4074 9.44824 12.4015C9.44824 13.3955 10.2974 14.2014 11.3448 14.2014Z"
                fill="white"
              ></path>
              <path
                d="M25.9989 15.4688L21.3278 19.2012C20.7752 19.6428 20.0993 19.9222 19.3825 20.0054C18.6656 20.0886 17.9387 19.972 17.2904 19.6699L13.5988 17.9489C13.0423 17.6896 12.4264 17.5663 11.8069 17.5902C11.1875 17.6141 10.5841 17.7845 10.0516 18.0859L6.00098 20.3788V20.6554C6.00089 21.226 6.11915 21.7909 6.34906 22.318C6.57896 22.8452 6.91598 23.3241 7.34087 23.7276C7.76576 24.131 8.27022 24.4511 8.82541 24.6694C9.38059 24.8878 9.97563 25.0002 10.5766 25.0002H21.4247C22.6381 24.9998 23.8017 24.5419 24.6595 23.7271C25.5173 22.9123 25.9991 21.8074 25.9989 20.6554V15.4688Z"
                fill="#4579C7"
              ></path>
            </svg>
            <svg v-else width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M7 9C7 6.79086 8.79086 5 11 5L18.6383 5C19.1906 5 19.6383 5.44772 19.6383 6V6.92308C19.6383 9.13222 21.4292 10.9231 23.6383 10.9231H24C24.5523 10.9231 25 11.3708 25 11.9231V23C25 25.2091 23.2091 27 21 27H11C8.79086 27 7 25.2091 7 23V9Z"
                fill="#F8CA27"
              ></path>
              <g filter="url(#filter0_d_602_422)">
                <path
                  d="M19.6602 6.92458V5.84766L24.4126 10.9246H23.6602C21.451 10.9246 19.6602 9.13372 19.6602 6.92458Z"
                  fill="#F8EDC7"
                ></path>
              </g>
              <path
                d="M20.2557 12H11.7443C11.3332 12 11 12.3358 11 12.75C11 13.1642 11.3332 13.5 11.7443 13.5H20.2557C20.6668 13.5 21 13.1642 21 12.75C21 12.3358 20.6668 12 20.2557 12Z"
                fill="#F8EDC7"
              ></path>
              <path
                d="M20.2557 16L11.7443 16.0017C11.3332 16.0017 11 16.3371 11 16.7509C11 17.1646 11.3332 17.5 11.7443 17.5L20.2557 17.4983C20.6668 17.4983 21 17.1629 21 16.7491C21 16.3354 20.6668 16 20.2557 16Z"
                fill="#F8EDC7"
              ></path>
              <path
                d="M15.3575 20H11.6425C11.2876 20 11 20.3358 11 20.75C11 21.1642 11.2876 21.5 11.6425 21.5H15.3575C15.7124 21.5 16 21.1642 16 20.75C16 20.3358 15.7124 20 15.3575 20Z"
                fill="#F8EDC7"
              ></path>
              <defs>
                <filter
                  id="filter0_d_602_422"
                  x="19.1602"
                  y="5.34766"
                  width="7.75195"
                  height="8.07617"
                  filterUnits="userSpaceOnUse"
                  color-interpolation-filters="sRGB"
                >
                  <feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood>
                  <feColorMatrix
                    in="SourceAlpha"
                    type="matrix"
                    values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
                    result="hardAlpha"
                  ></feColorMatrix>
                  <feOffset dx="1" dy="1"></feOffset>
                  <feGaussianBlur stdDeviation="0.75"></feGaussianBlur>
                  <feComposite in2="hardAlpha" operator="out"></feComposite>
                  <feColorMatrix
                    type="matrix"
                    values="0 0 0 0 0.591623 0 0 0 0 0.452482 0 0 0 0 0.0698445 0 0 0 0.25 0"
                  ></feColorMatrix>
                  <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_602_422"></feBlend>
                  <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_602_422" result="shape"></feBlend>
                </filter>
              </defs>
            </svg>
          </div>
          <div class="ab-item-info">
            <p class="abi-info1 ellipsis">{{ file.name }}</p>
            <p class="abi-info2 ellipsis">
              {{ file.loading ? '上传中...' : getFileExtension(file.name) + ' ' + formatFileSize(file.size) }}
            </p>
          </div>
          <div class="ab-item-close" @click="handleFileRemove(file)">
            <svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path
                fill-rule="evenodd"
                clip-rule="evenodd"
                d="M7.45.549a.777.777 0 0 1 0 1.098L1.648 7.451A.776.776 0 1 1 .55 6.353L6.353.55a.776.776 0 0 1 1.098 0z"
                fill="#868686"
              ></path>
              <path
                fill-rule="evenodd"
                clip-rule="evenodd"
                d="M.55.548a.776.776 0 0 1 1.097 0l5.804 5.805A.777.777 0 0 1 6.353 7.45L.549 1.646a.777.777 0 0 1 0-1.098z"
                fill="#868686"
              ></path>
            </svg>
          </div>
        </div>
      </div>
    </div>

    <div class="dialogue">
      <div class="textarea-wrap">
        <textarea v-model.trim="message" id="chat-textarea" placeholder="给 Omni 发送消息 "></textarea>
      </div>

      <div class="mb-btn-groups d-flex flex-ju-sb">
        <div class="d-flex">
          <button class="mb-btn" :class="btnStatus.deepThink && 'btn-primary'" @click="handleBtnStatus('deepThink')">
            <div class="mb-icon">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M2.656 17.344c-1.016-1.015-1.15-2.75-.313-4.925.325-.825.73-1.617 1.205-2.365L3.582 10l-.033-.054c-.5-.799-.91-1.596-1.206-2.365-.836-2.175-.703-3.91.313-4.926.56-.56 1.364-.86 2.335-.86 1.425 0 3.168.636 4.957 1.756l.053.034.053-.034c1.79-1.12 3.532-1.757 4.957-1.757.972 0 1.776.3 2.335.86 1.014 1.015 1.148 2.752.312 4.926a13.892 13.892 0 0 1-1.206 2.365l-.034.054.034.053c.5.8.91 1.596 1.205 2.365.837 2.175.704 3.911-.311 4.926-.56.56-1.364.861-2.335.861-1.425 0-3.168-.637-4.957-1.757L10 16.415l-.053.033c-1.79 1.12-3.532 1.757-4.957 1.757-.972 0-1.776-.3-2.335-.86zm13.631-4.399c-.187-.488-.429-.988-.71-1.492l-.075-.132-.092.12a22.075 22.075 0 0 1-3.968 3.968l-.12.093.132.074c1.308.734 2.559 1.162 3.556 1.162.563 0 1.006-.138 1.298-.43.3-.3.436-.774.428-1.346-.008-.575-.159-1.264-.449-2.017zm-6.345 1.65l.058.042.058-.042a19.881 19.881 0 0 0 4.551-4.537l.043-.058-.043-.058a20.123 20.123 0 0 0-2.093-2.458 19.732 19.732 0 0 0-2.458-2.08L10 5.364l-.058.042A19.883 19.883 0 0 0 5.39 9.942L5.348 10l.042.059c.631.874 1.332 1.695 2.094 2.457a19.74 19.74 0 0 0 2.458 2.08zm6.366-10.902c-.293-.293-.736-.431-1.298-.431-.998 0-2.248.429-3.556 1.163l-.132.074.12.092a21.938 21.938 0 0 1 3.968 3.968l.092.12.074-.132c.282-.504.524-1.004.711-1.492.29-.753.442-1.442.45-2.017.007-.572-.129-1.045-.429-1.345zM3.712 7.055c.202.514.44 1.013.712 1.493l.074.13.092-.119a21.94 21.94 0 0 1 3.968-3.968l.12-.092-.132-.074C7.238 3.69 5.987 3.262 4.99 3.262c-.563 0-1.006.138-1.298.43-.3.301-.436.774-.428 1.346.007.575.159 1.264.448 2.017zm0 5.89c-.29.753-.44 1.442-.448 2.017-.008.572.127 1.045.428 1.345.293.293.736.431 1.298.431.997 0 2.247-.428 3.556-1.162l.131-.074-.12-.093a21.94 21.94 0 0 1-3.967-3.968l-.093-.12-.074.132a11.712 11.712 0 0 0-.71 1.492z"
                  fill="currentColor"
                  stroke="currentColor"
                  stroke-width=".1"
                ></path>
                <path
                  d="M10.706 11.704A1.843 1.843 0 0 1 8.155 10a1.845 1.845 0 1 1 2.551 1.704z"
                  fill="currentColor"
                  stroke="currentColor"
                  stroke-width=".2"
                ></path>
              </svg>
            </div>
            <span>深度思考 (R1)</span>
          </button>
          <!-- <button
            class="mb-btn"
            :class="btnStatus.onlineSearch && 'btn-primary'"
            @click="handleBtnStatus('onlineSearch')"
          >
            <div class="mb-icon">
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="10" cy="10" r="9" stroke="currentColor" stroke-width="1.8"></circle>
                <path
                  d="M10 1c1.657 0 3 4.03 3 9s-1.343 9-3 9M10 19c-1.657 0-3-4.03-3-9s1.343-9 3-9M1 10h18"
                  stroke="currentColor"
                  stroke-width="1.8"
                ></path>
              </svg>
            </div>
            <span>联网搜索</span>
          </button> -->
          <button
            class="mb-btn"
            :class="btnStatus.relatedAttachment && 'btn-primary'"
            @click="handleBtnStatus('relatedAttachment')"
          >
            <span>关联历史附件</span>
          </button>
          <ElInput
            v-show="btnStatus.relatedAttachment"
            v-model="attachmentKeywords"
            class="mb-input"
            placeholder="请输入关键词"
          />
        </div>
        <div>
          <el-upload
            class="upload-demo"
            ref="upload"
            action="/myapp/api/file/search-file"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleUploadChange"
            :file-list="uploadFileList"
          >
            <button class="upload button-empty-style">
              <div class="upload-icon">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 20" fill="none">
                  <path
                    d="M7 20c-1.856-.002-3.635-.7-4.947-1.94C.74 16.819.003 15.137 0 13.383V4.828a4.536 4.536 0 0 1 .365-1.843 4.75 4.75 0 0 1 1.087-1.567A5.065 5.065 0 0 1 3.096.368a5.293 5.293 0 0 1 3.888 0c.616.244 1.174.6 1.643 1.05.469.45.839.982 1.088 1.567.25.586.373 1.212.364 1.843v8.555a2.837 2.837 0 0 1-.92 2.027A3.174 3.174 0 0 1 7 16.245c-.807 0-1.582-.3-2.158-.835a2.837 2.837 0 0 1-.92-2.027v-6.22a1.119 1.119 0 1 1 2.237 0v6.22a.777.777 0 0 0 .256.547.868.868 0 0 0 .585.224c.219 0 .429-.08.586-.224a.777.777 0 0 0 .256-.546V4.828A2.522 2.522 0 0 0 7.643 3.8a2.64 2.64 0 0 0-.604-.876 2.816 2.816 0 0 0-.915-.587 2.943 2.943 0 0 0-2.168 0 2.816 2.816 0 0 0-.916.587 2.64 2.64 0 0 0-.604.876 2.522 2.522 0 0 0-.198 1.028v8.555c0 1.194.501 2.339 1.394 3.183A4.906 4.906 0 0 0 7 17.885a4.906 4.906 0 0 0 3.367-1.319 4.382 4.382 0 0 0 1.395-3.183v-6.22a1.119 1.119 0 0 1 2.237 0v6.22c-.002 1.754-.74 3.436-2.052 4.677C10.635 19.3 8.856 19.998 7 20z"
                    fill="currentColor"
                  ></path>
                </svg>
              </div>
            </button>
          </el-upload>
          <button
            class="send button-empty-style"
            :class="!sendMessageBtnDisabled && 'btn-primary'"
            :disabled="sendMessageBtnDisabled"
            @click="sendMessage"
          >
            <div class="upload-icon">
              <svg width="14" height="16" viewBox="0 0 14 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  fill-rule="evenodd"
                  clip-rule="evenodd"
                  d="M7 16c-.595 0-1.077-.462-1.077-1.032V1.032C5.923.462 6.405 0 7 0s1.077.462 1.077 1.032v13.936C8.077 15.538 7.595 16 7 16z"
                  fill="currentColor"
                ></path>
                <path
                  fill-rule="evenodd"
                  clip-rule="evenodd"
                  d="M.315 7.44a1.002 1.002 0 0 1 0-1.46L6.238.302a1.11 1.11 0 0 1 1.523 0c.421.403.421 1.057 0 1.46L1.838 7.44a1.11 1.11 0 0 1-1.523 0z"
                  fill="currentColor"
                ></path>
                <path
                  fill-rule="evenodd"
                  clip-rule="evenodd"
                  d="M13.685 7.44a1.11 1.11 0 0 1-1.523 0L6.238 1.762a1.002 1.002 0 0 1 0-1.46 1.11 1.11 0 0 1 1.523 0l5.924 5.678c.42.403.42 1.056 0 1.46z"
                  fill="currentColor"
                ></path>
              </svg>
            </div>
          </button>
        </div>
      </div>
    </div>

    <div class="tip-text">内容由 AI 生成，请仔细甄别</div>

    <!-- 隐藏的图片组件 -->
    <el-image
      ref="hiddenImage"
      style="display: none"
      :src="currentImageUrl"
      :preview-src-list="[currentImageUrl]"
      :initial-index="initialImageIndex"
    ></el-image>

    <HistoryAttachmentsVue v-show="btnStatus.relatedAttachment" :list="historyAttachmentList" />
  </div>
</template>

<script>
// request
import {
  postDialogueID,
  postChatFlux,
  postChatAsk,
  getSearchHisDialogue,
  uploadParseImage,
  uploadParseFile,
  searchFileBykw
} from '@/api/index/index.js'

// util
import { setUserInfo, getBtnStatus, setBtnStatus } from '@/utils/storage.js'
import { processContent } from '@/utils/dataParse.js'
import { isImageByMIME, formatFileSize, getFileExtension, fileUrlParse } from '@/utils/file'
import { getStorageUserId } from '@/utils/profile'

// store
// 对象里有新的绑定在给定命名空间值上的组件绑定辅助函数
import { createNamespacedHelpers } from 'vuex'
const { mapMutations } = createNamespacedHelpers('index')

// mock
// import { str3 as mockData } from '@/views/Index/mock.js'

// data
import { createChatItem } from './data'

import HistoryAttachmentsVue from './../List/HistoryAttachments.vue'
export default {
  name: 'DialogueBox',

  components: { HistoryAttachmentsVue },

  data: () => ({
    message: '',
    messageDuplicate: '',
    attachmentKeywords: '',

    questionNum: 1, // 第几个问题
    chatId: null, // 对话id

    uploadFileList: [],
    currentImageUrl: '',
    initialImageIndex: 0,

    historyAttachmentList: [],

    // 按钮状态
    btnStatus: getBtnStatus() || {
      deepThink: false,
      onlineSearch: false,
      relatedAttachment: false
    }
  }),

  computed: {
    sendMessageBtnDisabled() {
      if (this.btnStatus.relatedAttachment) {
        return this.message.length === 0 || this.attachmentKeywords.length === 0
      } else {
        return !this.message.length
      }
    },

    chatList() {
      return this.$store.state.index.chatList
    },
  },

  methods: {
    ...mapMutations(['SET_chatList', 'SET_isRenderChatList', 'SET_chatTitle']),

    handleBtnStatus(v) {
      this.btnStatus[v] = !this.btnStatus[v]
      setBtnStatus(this.btnStatus)
    },

    /* 图片附件相关 */
    formatFileSize,
    getFileExtension,
    isImageByMIME,
    handleFileRemove(file) {
      this.uploadFileList = this.uploadFileList.filter(f => f !== file)
    },
    handleUploadChange(file, fileList) {
      // console.log(file, fileList)
      this.$set(file, 'loading', true)
      this.uploadFileList.push(file)

      if (isImageByMIME(file.raw.type)) {
        uploadParseImage(file.raw, { userID: getStorageUserId() })
          .then(res => {
            // console.log('uploadParseImage', res)
            res.url = fileUrlParse(res.url)
            file.loading = false
            Object.assign(file, res)
          })
          .catch(err => console.log(err))
      } else {
        uploadParseFile(file.raw, { userID: getStorageUserId() })
          .then(res => {
            // console.log('uploadParseFile', res)
            const data = JSON.parse(res.text)
            data.url = fileUrlParse(data.url)
            file.loading = false
            Object.assign(file, data)
          })
          .catch(err => console.log(err))
      }
    },
    handleFilePreview(file) {
      if (isImageByMIME(file.raw.type)) {
        this.currentImageUrl = file.url
        // 触发预览（需要nextTick确保DOM更新）
        this.$nextTick(() => {
          this.$refs.hiddenImage.clickHandler()
        })
      } else {
        window.open(file.url)
      }
    },
    /* 图片附件相关结束 */

    /* 重新生成对话 */
    chatReBuild(data) {
      console.log('重新生成对话', data)
      const params = { ...data }
      params.loadingChat = true
      params.answer_reveal = ''
      params.answer = ''
      params.thoughts = ''
      params.thoughts_reveal = ''
      this.sendMessage(true, params)
      // this.messageDuplicate = this.data.question
      /* const isDeepThink = this.btnStatus.deepThink
      if (isDeepThink) {
        this.postChatFlux()
      } else {
        this.postChatAsk()
      } */
    },

    createRequestParameter(reBuild, data) {
      const questionId = this.chatList.length || this.questionNum++
      let content = ''
      let uploadFileList = []
      /* 
        {
          "content": "简单总结一下",//提问的问题
          "questionId": "3",//对话中的第几个问题
          "dialogueId":"1",//对话id
          "mimeType":"3",//1  表示不包含附件  2 表示是附件  3表示是图片
          "documenID":"40"// mimeType  为  2 3的时候 必传 附件id
        }
      */

      if (reBuild === true) {
        content = data.question
        uploadFileList = data.fileList || []
      } else {
        content = this.messageDuplicate
        uploadFileList = this.uploadFileList
      }

      const params = {
        // content: 'AI会取代人类吗？',
        content,
        questionId,
        dialogueId: this.chatId,
        mimeType: null,
        userID: getStorageUserId()
      }

      /* 判断是否有附件 */
      if (uploadFileList.length > 0) {
        const isImage = isImageByMIME(uploadFileList[0].raw.type)
        if (isImage) {
          params.mimeType = '3'
          params.documenID = uploadFileList[0].imageid || uploadFileList[0].fileid
        } else {
          params.mimeType = '2'
          params.documenID = uploadFileList[0].fileid
        }
      } else {
        params.mimeType = '1'
      }
      // debugger

      /* 如果 questionId 为 1，说明是第一次问问题，更新左侧栏对话记录 */
      /* if (questionId === 1) {
        window.setTimeout(() => {
          this.$bus.$emit('update-dialog-history')
        }, 1000)
      } */
      return params
    },

    /* ***  数据请求开始 *** */
    async sendMessage(reBuild, data) {
      // console.log(11111, data.question);
      // debugger
      this.SET_isRenderChatList(false)
      /* 是否为重新生成 */
      if (reBuild === true) {
        this.messageDuplicate = data.question
      } else {
        this.messageDuplicate = this.message
        if (this.questionNum === 1) {
          this.SET_chatTitle(this.messageDuplicate)
        }
      }
      this.message = ''
      // console.log('this.messageDuplicate', this.messageDuplicate);
      // return

      /* 先获取对话id
      根据获取到的id去请求接口
      */
      this.chatId = await this.getChatId()
      /* 判断是否深度思考 */
      const isDeepThink = this.btnStatus.deepThink
      if (isDeepThink) {
        this.postChatFlux(reBuild, data)
      } else {
        this.postChatAsk(reBuild, data)
      }

      if (this.attachmentKeywords) {
        this.searchFileBykw()
      }
    },

    /* 获取对话id */
    getChatId() {
      let cb = null
      const promise = new Promise(resolve => {
        cb = function (p) {
          resolve(p)
        }
      })

      const chatId = this.$route.query.chatId || ''
      /* 有对话 id 不必再次请求 */
      if (chatId) {
        cb(chatId)
      } else {
        postDialogueID().then(res => {
          if (res.code !== 200) return
          const data = JSON.parse(res.data)
          // console.log('data', data)
          setUserInfo(data)
          cb(data.id)
          this.$router.push({ name: 'index', query: { chatId: data.id } })
        })
      }

      return promise
    },

    /* 没有选择深度思考，则是简单对话回答问题 */
    postChatAsk(reBuild, data) {
      const item = reBuild === true ? data : createChatItem(this.messageDuplicate, { fileList: this.uploadFileList })
      this.SET_chatList(item)
      postChatAsk(this.createRequestParameter(reBuild, data))
        .then(res => {
          // console.log('无深度思考---', res)
          item.loadingChat = false
          item.answer = res.content
          this.SET_chatList(item)
        })
        .catch(err => {
          // console.log(err)
          const res = err.response || {}
          const message = res.data?.message || '系统错误，请稍后再试'
          item.loadingChat = false
          item.answer = message
          this.SET_chatList(item)
        })
    },

    /* 选择了深度思考，并且没有上传附件，图片
      返回思考推理过程 */
    postChatFlux(reBuild, data) {
      const item = reBuild === true ? data : createChatItem(this.messageDuplicate, { fileList: this.uploadFileList })
      this.SET_chatList(item)
      /* 
      {
          "content": "AI会取代人类吗？",//提问的问题
          "stream": true,//开启流式响应
          "questionid": "2",//对话中的第几个问题
          "dialogueid":"1"//对话id
        }
      */

      /* 本地模拟 */
      /* const processed = processContent(mockData)
      setTimeout(() => {
        item.loadingChat = false
        Object.assign(item, processed)
        this.SET_chatList(item)
      }, 2000) */

      /* axios 请求方案 */
      postChatFlux(this.createRequestParameter(reBuild, data), {
        responseType: 'stream'
      })
        .then(res => {
          // console.log(res)
          const processed = processContent(res)
          // console.log(processed)
          item.loadingChat = false
          Object.assign(item, processed)
          this.SET_chatList(item)
        })
        .catch(err => {
          const res = err.response || {}
          const message = res.data?.message || '系统错误，请稍后再试'
          item.loadingChat = false
          item.answer = message
          this.SET_chatList(item)
        })

      /* fetch 请求方案 */
      /* const requestOptions = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          content: 'AI会取代人类吗？',
          questionid,
          dialogueid: this.chatId
        })
      }
      async function fetchStream() {
        try {
          const response = await fetch('/ds/myapp/api/chat/flux', requestOptions)

          const reader = response.body.getReader()
          const decoder = new TextDecoder()
          let buffer = ''

          while (true) {
            const { done, value } = await reader.read()
            if (done) break

            buffer += decoder.decode(value, { stream: true })

            // 事件处理
            while (buffer.indexOf('\n') > -1) {
              const lineEnd = buffer.indexOf('\n')
              const line = buffer.slice(0, lineEnd)
              buffer = buffer.slice(lineEnd + 1)

              if (line.startsWith('data:')) {
                const content = line.slice(5).trim()
                console.log('content-----', content)
                if (content) {
                }
              }
            }
          }
        } catch (error) {
          console.error('Stream error:', error)
        }
      } */
    },

    /* 根据关键词检索相关附件 */
    searchFileBykw() {
      // searchFileBykw({ keyword: this.attachmentKeywords, tags: 'file' })
      searchFileBykw({ keyword: this.attachmentKeywords })
        .then(res => {
          console.log('根据关键词检索相关附件', res)
          this.historyAttachmentList = res
        })
        .catch(err => console.log(err))
    },

    /* 根据对话id，获取对话记录 */
    async getSearchHisDialogue() {
      const id = this.$route.query.chatId
      if (!id) return

      this.SET_chatTitle()
      const res = await getSearchHisDialogue({
        page: '0',
        size: '10',
        dialogueId: id
      })
      const content = res.content || []
      if (!content.length) return

      const data = []
      for (let i = content.length - 1; i > -1; i--) {
        const con = content[i]
        let opts = {}
        if (con.answer.startsWith('思考')) {
          const pc = processContent(con.answer)
          opts = {
            ...pc,
            answer_reveal: pc.answer,
            thoughts_reveal: pc.thoughts,
            showSplitLine: true,
            showBtns: true,
            loadingChat: false
          }
        } else {
          opts = {
            answer: con.answer,
            answer_reveal: con.answer,
            showSplitLine: false,
            showBtns: true,
            loadingChat: false
          }
        }
        if (con.fileurl && con.fileurl !== '-1') {
          opts.fileList = [
            {
              raw: { type: con.filename.split('.').at(-1) },
              name: con.filename,
              size: Number(con.filesize),
              fileid: con.fileid
            }
          ]
        }
        const item = createChatItem(con.keyword, opts)
        data.push(item)
      }

      // console.log('data', data)
      this.SET_isRenderChatList(true) // 表示回显，回显不显示打印效果
      this.SET_chatList(data)
      this.SET_chatTitle(data.at(-1).question)
    }
  },

  watch: {
    '$route.query.chatId'(v) {
      this.getSearchHisDialogue()
    }
  },

  mounted() {
    this.$bus.$on('chat-rebuild', this.chatReBuild)

    this.getSearchHisDialogue()
  },

  beforeDestroy() {
    this.$bus.$off('chat-rebuild')
  }
}
</script>

<style lang="less" scoped></style>
